import React, { Component } from 'react'
import { createRoot } from 'react-dom/client'
import './style/base.css'
import './style/index.css'
import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: '吃饭',
        checked: true,
      },
      {
        id: 2,
        name: '睡觉',
        checked: false,
      },
      {
        id: 3,
        name: '打游戏',
        checked: false,
      },
    ],
    // 三个值 all active copleted
    type: 'all',
  }
  render() {
    const { list, type } = this.state
    return (
      <section className="todoapp">
        <TodoHeader AddTodo={this.AddTodo}></TodoHeader>
        <TodoMain
          list={list}
          type={type}
          DelTodoById={this.DelTodoById}
          checkedAll={this.checkedAll}
          ChangeTodoDyId={this.ChangeTodoDyId}
          EditTodo={this.EditTodo}
        ></TodoMain>
        <TodoFooter
          list={list}
          type={type}
          clearCompleted={this.clearCompleted}
          changeType={this.changeType}
        ></TodoFooter>
      </section>
    )
  }

  //删除事件
  DelTodoById = (id) => {
    // console.log('id', id)
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }

  //切换勾选是否完成
  ChangeTodoDyId = (id) => {
    this.setState({
      list: this.state.list.map((item) => {
        //根据id把item中的checked取反
        if (item.id === id) {
          return { ...item, checked: !item.checked }
        } else {
          return item
        }
      }),
    })
  }

  //添加Todo
  AddTodo = (name) => {
    this.setState({
      list: [
        {
          id: Date.now(),
          name: name,
          checked: false,
        },
        ...this.state.list,
      ],
    })
  }

  //提交修改后的Todo
  EditTodo = (id, name) => {
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return {
            id: item.id,
            name: name,
            checked: item.checked,
          }
        } else return item
      }),
    })
  }

  //清除已完成TOdo
  clearCompleted = () => {
    this.setState({
      list: this.state.list.filter((item) => item.checked === false),
    })
  }

  changeType = (type) => {
    this.setState({
      type,
    })
  }

  checkedAll = (checked) => {
    this.setState({
      list: this.state.list.map((item) => {
        return {
          ...item,
          checked,
        }
      }),
    })
  }
  ////////
}

// 渲染组件
// ReactDOM.render(<App />, document.getElementById('root'))
createRoot(document.querySelector('#root')).render(<App />)
